/**
 * @Creator: eyes
 * @Date: 2019/12/23
 * 组件: 日期区间选择+显示粒度联动选择.
 * 是否为受控组件: 是.
 * 功能介绍:
 *  接收业务方参数dateRange: [moment, moment], duration: TIME_DURATION
 *  自动计算不同dateRange值下的duration可选列表.
 *  目前的规则, 显示粒度可选项只有一个: 当日期跨天选择时, 粒度为天; 当日期只选择一天时, 粒度为十分钟.
 */

import React, {useCallback} from 'react';
import {DatePicker, Select} from 'antd';
import moment from 'moment';
import {popUpContainer} from '../../utils';
import {getDurationOptions, getDefaultDuration} from './utils';

import './index.styl';

const {RangePicker} = DatePicker;
const {Option} = Select;

export default props => {
    const {
        dateRange = [moment(), moment()],
        duration = getDefaultDuration(dateRange),
        setDateRangeAndDuration,
    } = props;

    const durationOptions = getDurationOptions(dateRange);

    const onDateChange = useCallback((dates, dateStrings) => {
        setDateRangeAndDuration({
            dateRange: dates,
            duration: getDefaultDuration(dates),
        });
    }, [setDateRangeAndDuration]);

    return (
        <div className="date-range-and-duration-selector-container">
            <span className="selector-title">日期</span>
            <RangePicker
                allowClear={false}
                format="YYYY-MM-DD"
                onChange={onDateChange}
                value={dateRange}
                getCalendarContainer={popUpContainer}
                style={{marginLeft: 10, width: 260}}
            />
            <Select value={duration} className="duration-selector" getPopupContainer={popUpContainer}>
                {
                    durationOptions.map(_ => (
                        <Option value={_.value} key={_.value}>
                            {_.label}
                        </Option>
                    ))
                }
            </Select>
        </div>
    );
};
